package net.huashitong.Project.service;

import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import com.sirdc.modules.utils.date.DateUtils;
import net.huashitong.Project.entity.EarlyWarningNode;
import net.huashitong.Project.entity.NewProjects;
import net.huashitong.Project.util.MessageUtil;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.entity.NodeNewtemplet;
import net.huashitong.node.filter.NodeNewschedulesFilter;
import net.huashitong.node.filter.NodeNewtempletFilter;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.node.service.NodeNewtempletService;
import net.huashitong.node.utile.DateUtil;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.service.GradePointService;
import net.huashitong.oversee.service.ScoreSummaryService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.taskGroup.service.JobGroupService;
import net.huashitong.user.entity.Message;
import net.huashitong.user.entity.SuperviseUser;
import net.huashitong.user.entity.TemporaryMessage;
import net.huashitong.user.filter.MessageFilter;
import net.huashitong.user.service.MessageService;
import net.huashitong.user.service.SuperviseUserService;
import net.huashitong.user.service.TemporaryMessageService;
import net.huashitong.utils.UtilsTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static net.huashitong.Project.util.TimeDataDealWithUtil.dealWithNull;

@Service
public class EarlyWarningService {

    Logger logger = LoggerFactory.getLogger("EarlyWarningService");
    @Autowired
    private NewProjectsService nService;
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;
    @Autowired
    private EarlyWarningNodeService ewns;
    @Autowired
    private NodeNewtempletService nodeNewtempletService;
    @Autowired
    private MessageService ms;
    @Autowired
    private TemporaryMessageService tms;
    @Autowired
    private SuperviseUserService superviseUserService;
    @Autowired
    private MessageUtil mu;
    @Autowired
    private SupervisionTaskService taskjobService;
    @Autowired
    private JobGroupService jobGroupService;
    @Autowired
    private ScoreSummaryService scoreSummaryService;
    @Autowired
    private GradePointService gradePointService;


    /**
     * 存储逾期数据
     */
    public void EarlyWarningSch() throws ParseException {
        logger.info(DateUtils.getDateTime() + "*****************存储逾期数据定时任务开始*****************");
        System.out.println(DateUtils.getDateTime() + "*****************存储逾期数据定时任务开始*****************");
        if (!DateUtil.isWEEK(new Date())) {
            DateFormat format1 = new SimpleDateFormat("yyyy.MM.dd");
            Map<String, EarlyWarningNode> eMap = new HashMap<>();
            //获取所有预警未处理信息
            List<EarlyWarningNode> earlyWarningNodes = ewns.getAllEarlyWarningNodeNoDealWith();
            for (EarlyWarningNode warningNode : earlyWarningNodes) {
                if (!eMap.containsKey(warningNode.getNodeSysId())) {
                    eMap.put(warningNode.getNodeSysId(), warningNode);
                }
            }
            //节点列表添加更新预警信息(获取进行中的小节点、过滤不需要的节点)
            List<NodeNewschedules> list = nodeNewschedulesService.getListByType();
            for (NodeNewschedules nodeN : list) {
                //删除eMap里面的记录
                if (eMap.containsKey(nodeN.getSysId())) {
                    eMap.remove(nodeN.getSysId());
                }
                if (ObjectUtils.isNotBlank(nodeN.getPlanBeginDate()) && ObjectUtils.isNotBlank(nodeN.getPlanTime())) {
                    //判断逾期
                    Date bdate = format1.parse(nodeN.getPlanBeginDate());
                    List<Date> Datelist = DateUtil.getBetweenDates(bdate, new Date());
                    int zxz = DateUtil.getStatistics(Datelist);     //除去周末两天项目至今所用的时间（天）
                    int planTime = Integer.parseInt(nodeN.getPlanTime());
                    //int zxz = DateUtil.betweenTwoDateNum(DateUtil.addDays(nodeN.getPlanBeginDate(), Integer.parseInt(nodeN.getPlanTime()) - 1), DateUtil.getDate());
                    if (zxz > planTime) {       //已经逾期
                        int num = zxz - planTime;
                        EarlyWarningNode ewn = ewns.queryEarlyWarningNodeByNodeSysId(nodeN.getSysId());
                        if (ObjectUtils.isBlank(ewn)) {
                            EarlyWarningNode ewnd = new EarlyWarningNode();
                            NewProjects np = nService.getById(nodeN.getProjectId());
                            ewnd.setProjectName(np.getName());
                            ewnd.setProjectId(nodeN.getProjectId());
                            ewnd.setNodeSysId(nodeN.getSysId());
                            ewnd.setNodeId(nodeN.getNodeId());
                            ewnd.setNodeName(nodeN.getNodeName());
                            ewnd.setResDept(nodeN.getResDept());
                            ewnd.setResUser(nodeN.getResUser());
                            ewnd.setResUserPhone(nodeN.getResUserPhone());
                            ewnd.setOperatorUser(nodeN.getOperatorUser());
                            ewnd.setOperatorPhone(nodeN.getOperatorPhone());
                            ewnd.setNodeType(nodeN.getNodeType());
                            ewnd.setFactFinishDate(nodeN.getFactFinishDate());
                            ewnd.setPlanBeginDate(nodeN.getPlanBeginDate());
                            ewnd.setFactTime(nodeN.getFactTime());
                            ewnd.setPlanTime(nodeN.getPlanTime());
                            ewnd.setMessageMumber("0");
                            ewnd.setStatus("1");
                            ewnd.setState("0");
                            ewnd.setNumber(num + "");
                            ewns.save(ewnd);
                            NodeNewschedules node2 = nodeNewschedulesService.getById(nodeN.getSysId());
                            node2.setIsDelay("1");
                            nodeNewschedulesService.update(node2);

                            /**
                             * 保存督查任务数据
                             */
                            taskjobService.saveAutoTaskJob(ewnd);
                        } else if ("0".equals(ewn.getState())) {        //目前逾期列表已经有记录，如果处理状态显示未处理
                            //如果计划时间有改动，就生成新的预警信息
                            if (!nodeN.getPlanTime().equals(ewn.getPlanTime())) {
                                EarlyWarningNode ewnd = new EarlyWarningNode();
                                NewProjects np = nService.getById(nodeN.getProjectId());
                                ewnd.setProjectName(np.getName());
                                ewnd.setProjectId(nodeN.getProjectId());
                                ewnd.setNodeSysId(nodeN.getSysId());
                                ewnd.setNodeId(nodeN.getNodeId());
                                ewnd.setNodeName(nodeN.getNodeName());
                                ewnd.setResDept(nodeN.getResDept());
                                ewnd.setResUser(nodeN.getResUser());
                                ewnd.setResUserPhone(nodeN.getResUserPhone());
                                ewnd.setOperatorUser(nodeN.getOperatorUser());
                                ewnd.setOperatorPhone(nodeN.getOperatorPhone());
                                ewnd.setNodeType(nodeN.getNodeType());
                                ewnd.setFactFinishDate(nodeN.getFactFinishDate());
                                ewnd.setPlanBeginDate(nodeN.getPlanBeginDate());
                                ewnd.setFactTime(nodeN.getFactTime());
                                ewnd.setPlanTime(nodeN.getPlanTime());
                                ewnd.setStatus("1");
                                ewnd.setState("0");
                                ewnd.setMessageMumber("0");
                                ewnd.setNumber(num + "");
                                ewns.save(ewnd);
                                /**
                                 * 保存督查任务数据
                                 */
                                taskjobService.saveAutoTaskJob(ewnd);
                                //将旧的预警记录改成已处理
                                ewn.setState("1");
                                ewns.update(ewn);
                            } else {
                                SupervisionTaskFilter filter = new SupervisionTaskFilter();
                                filter.setNodeSysId(ewn.getNodeSysId());
                                List<SupervisionTask> supervisionTasks = taskjobService.querySupervisionTaskByFilter(filter);
                                if (supervisionTasks.size() > 0) {
                                    SupervisionTask task = supervisionTasks.get(0);
                                    task.setOverdueDays(num + "");
                                    taskjobService.update(task);
                                }
                                ewn.setNumber(num + "");
                                ewns.update(ewn);
                            }
                        }
                    }
                }
            }
            //剩下非进行中的预警信息做已处理更新
            for (String key : eMap.keySet()) {
                EarlyWarningNode earlyWarningNode = eMap.get(key);
                earlyWarningNode.setState("1");
                ewns.update(earlyWarningNode);
            }
        }

        //删掉考核记录中的重复数据
        gradePointService.deleteRepeatData();
        gradePointService.updateRank();
        //更新汇总得分
        scoreSummaryService.updateSummaryScore();
        logger.info(DateUtils.getDateTime() + "*****************更新汇总得分完成*****************");
        String updateScore = taskjobService.updateAllTaskRespAndSupervisionScore();
        if ("ok".equals(updateScore)) {
            logger.info(DateUtils.getDateTime() + "*****************更新督查任务得分完成*****************");
        }
        scoreSummaryService.updateSummaryScoreRank();
        scoreSummaryService.updateSummaryScoreTypeRank();
        logger.info(DateUtils.getDateTime() + "*****************存储逾期数据定时任务结束*****************");
        System.out.println(DateUtils.getDateTime() + "*****************存储逾期数据定时任务结束*****************");
    }

    /**
     * 发送预警短信
     */
    public void sendEarlyWarningSMS() throws ParseException {
        logger.info(DateUtils.getDateTime() + "*****************定时任务开始*****************");
        System.out.println(DateUtils.getDateTime() + "*****************定时任务开始*****************");
        List<EarlyWarningNode> list = ewns.queryEarlyWarningNodeListByStatus();
        //判断是否是周末，不是周末为true，进入
        if (!DateUtil.isWEEK(new Date())) {
            DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
            //查询所有发送过短信的预警信息
            List<SuperviseUser> suList1 = superviseUserService.querySuperviseUserListByIsLeader("2");
            if (list.size() > 0) {   //逾期列表不为执行
                for (EarlyWarningNode ewn : list) {  //逾期列表循环
                    //状态未处理进入
                    if ("0".equals(ewn.getState())) {
                        NewProjects np = nService.getById(ewn.getProjectId());
                        String deptName = "";
                        if (ewn.getResDept().contains("业主单位") || ewn.getResDept().contains("中介机构")) {
                            deptName = np.getResDept();
                        } else {
                            deptName = ewn.getResDept();
                        }
                        //逾期天数
                        // 逾期1天，发送攻坚办、节点经办人、责任人，每天发一次。
                        // 逾期5天，督查组
                        // 逾期10天，县分管领导
                        // 逾期15天，县长、书记
                        int number = Integer.parseInt(dealWithNull(ewn.getNumber()));
                        //计算当前时间与上次发短信时候距离天数
                        int status = Integer.parseInt(ewn.getStatus());
                        int messageMumber = Integer.parseInt(dealWithNull(ewn.getMessageMumber()));
                        if (messageMumber >= 0) {
                            if (number >= 5) {//发送---》责任单位负责人
                                //能被3整除怎发送短信
                                if ((number - 5) % 3 == 0) {
                                    Map<String, Object> mas = mu.superviseWarningMessage(ewn.getResUser(), ewn.getResUserPhone(),
                                            "《" + ewn.getProjectName() + "》", ewn.getNodeId(), ewn.getNodeName(), deptName);
                                    if ("0".equals(mas.get("code").toString())) {
                                        Message m = new Message();
                                        m.setRecipients(ewn.getResUser());
                                        m.setText(mas.get("text").toString());
                                        m.setType("2");
                                        m.setPhone(ewn.getResUserPhone());
                                        m.setMsg(mas.get("msg").toString());
                                        m.setProjectName(ewn.getProjectName());
                                        m.setResDept(ewn.getResDept());
                                        m.setNodeId(ewn.getNodeSysId());
                                        m.setState("0");
                                        ms.save(m);
                                    }
                                }
                            }
                            if (number >= 10) {//发送---》县分管领导
                                if ((number - 10) % 3 == 0) {
                                    /*预发短信*/
                                    TemporaryMessage tm = new TemporaryMessage();
                                    /*String position = ObjectUtils.isBlank(np.getPosition()) ? "县分管领导" : np.getPosition();*/
                                    tm.setText("【重大项目节点管理】" + np.getResUser()
                                            + ",您好！《" + ewn.getProjectName() + "》第" + ewn.getNodeId() + "节点" + ewn.getNodeName() + "已超期,请督促相关人员抓紧办理。");
                                    tm.setPhone(np.getResPhone());
                                    tm.setType("0");
                                    tm.setNodeId(ewn.getNodeId());
                                    tm.setRecipients(np.getResUser() + np.getPosition());
                                    tm.setResDept("县分管领导");
                                    tm.setNodeSysId(ewn.getNodeSysId());
                                    tm.setProjectName(ewn.getProjectName());
                                    tm.setState("0");
                                    tms.save(tm);

                                    /*Map<String, Object> mas = mu.superviseWarningMessage(np.getResUser(), np.getResPhone(),
                                            "《" + ewn.getProjectName() + "》", ewn.getNodeId(), ewn.getNodeName(), deptName);
                                    if ("0".equals(mas.get("code").toString())) {
                                        Message m = new Message();
                                        m.setRecipients(np.getResUser());
                                        m.setText(mas.get("text").toString());
                                        m.setType("2");
                                        m.setPhone(np.getResPhone());
                                        m.setMsg(mas.get("msg").toString());
                                        m.setProjectName(ewn.getProjectName());
                                        m.setResDept("县分管领导");
                                        m.setNodeId(ewn.getNodeSysId());
                                        m.setState("0");
                                        ms.save(m);
                                    }*/
                                }
                            }
                            if (number >= 15) {//发送---》县长和书记
                                if ((number - 15) % 3 == 0) {
                                    List<SuperviseUser> suList = superviseUserService.querySuperviseUserListByIsLeader("3");
                                    List<TemporaryMessage> temporaryMessages = new ArrayList<>();
                                    for (SuperviseUser sus : suList) {

                                        //根据nodeId查询小节点nodeId
                                        NodeNewtempletFilter filter = new NodeNewtempletFilter();
                                        filter.setNodeId(ewn.getNodeId());
                                        NodeNewtemplet t = nodeNewtempletService.queryNodeNewTempletByNode(filter);
                                        String smallNodeName = t.getNodeName();
                                        //根据nodeId查询大节点nodeId
                                        String[] bigNodeId = ewn.getNodeId().split("\\.");
                                        filter.setNodeId(bigNodeId[0]);
                                        NodeNewtemplet t1 = nodeNewtempletService.queryNodeNewTempletByNode(filter);
                                        String bigNodeName = t1.getNodeName();
                                        TemporaryMessage tm = new TemporaryMessage();
                                        tm.setText("【重大项目节点管理】" + sus.getName() + ",您好！《" + ewn.getProjectName() + "》第" + ewn.getNodeId() + "节点\"" + bigNodeName + "\"" + ewn.getNodeName() + "已超期,责任单位：" + deptName + ",请督促相关人员抓紧办理。系统地址：https://www.fzzhengxinyun.com ，帐号为个人手机号，初始密码123456");
                                        tm.setPhone(sus.getPhone());
                                        tm.setType("2");
                                        tm.setNodeId(ewn.getNodeId());
                                        tm.setRecipients(sus.getName());
                                        tm.setResDept("县领导");
                                        tm.setNodeSysId(ewn.getNodeSysId());
                                        tm.setProjectName(ewn.getProjectName());
                                        tm.setState("0");
                                        temporaryMessages.add(tm);
                                    }
                                    tms.batchSave(temporaryMessages);
                                }
                            }
                            status = status + 1;//发送次数
                        }
                        //经办人，攻坚办工作人员，督查组，逾期之后每天发送一次短信；
                        //发送----》经办人
                        Map<String, Object> ma = mu.earlyWarningMessage(ewn.getOperatorUser(),
                                ewn.getOperatorPhone(),
                                "《" + ewn.getProjectName() + "》",
                                ewn.getNodeId(),
                                ewn.getNodeName(),
                                deptName
                        );
                        if ("0".equals(ma.get("code").toString())) {
                            Message m1 = new Message();
                            m1.setRecipients(ewn.getOperatorUser());
                            m1.setText(ma.get("text").toString());
                            m1.setType("2");
                            m1.setPhone(ewn.getOperatorPhone());
                            m1.setMsg(ma.get("msg").toString());
                            m1.setProjectName(ewn.getProjectName());
                            m1.setResDept(ewn.getResDept());
                            m1.setNodeId(ewn.getNodeSysId());
                            m1.setState("0");
                            ms.save(m1);
                        }
                        //发送---》攻坚办工作人员，督查组
                        //攻坚办人员信息(放到循环外面)
//                        List<SuperviseUser> suList1 = superviseUserService.querySuperviseUserListByIsLeader("2");
                        //督查组人员列表
                        List<NodeNewschedules> sulist2;
                        String nodeId = ewn.getNodeId();            //节点id
                        String projectId = ewn.getProjectId();      //项目id
                        NodeNewschedulesFilter filter = new NodeNewschedulesFilter();
                        filter.setNodeId(nodeId);
                        filter.setProjectId(projectId);
                        sulist2 = nodeNewschedulesService.queryByFilter(filter);
                        String groupCode = null;
                        if (ObjectUtils.isNotBlank(sulist2)) {
                            groupCode = sulist2.get(0).getGroupCode();
                        }
                        //逾期发给督查组的信息删掉了
                        /*List<JobGroup> jobGroups = null;
                        if (ObjectUtils.isNotBlank(groupCode)) {
                            JobGroupFilter jobGroupFilter = new JobGroupFilter();
                            jobGroupFilter.setGroupCode(groupCode);
                            jobGroups = jobGroupService.queryByFilter(jobGroupFilter);
                        }*/
                        List<Message> messages1 = new ArrayList<>();
                        for (SuperviseUser su : suList1) {
                            System.out.println("攻坚作战");
                            Map<String, Object> mas = mu.superviseWarningMessage(su.getName(), su.getPhone(), "《" + ewn.getProjectName() + "》", ewn.getNodeId(), ewn.getNodeName(), deptName);
                            if ("0".equals(mas.get("code").toString())) {
                                Message m = new Message();
                                m.setRecipients(su.getName());
                                m.setText(mas.get("text").toString());
                                m.setType("2");
                                m.setPhone(su.getPhone());
                                m.setMsg(mas.get("msg").toString());
                                m.setProjectName(ewn.getProjectName());
                                m.setResDept("攻坚作战");
                                m.setNodeId(ewn.getNodeSysId());
                                m.setState("0");
                                messages1.add(m);
                            }
                        }
                        ms.batchSave(messages1);
                        /*List<Message> messages = new ArrayList<>();
                        if(ObjectUtils.isNotBlank(jobGroups)){
                            for (JobGroup j : jobGroups) {
                                System.out.println("督查部门");
                                Map<String, Object> mas = mu.superviseWarningMessage(j.getGroupContact(), j.getGroupTel(), "《" + ewn.getProjectName() + "》", ewn.getNodeId(), ewn.getNodeName());
                                if ("0".equals(mas.get("code").toString())) {
                                    Message m = new Message();
                                    m.setRecipients(j.getGroupContact());
                                    m.setText(mas.get("text").toString());
                                    m.setType("2");
                                    m.setPhone(j.getGroupTel());
                                    m.setMsg(mas.get("msg").toString());
                                    m.setProjectName(ewn.getProjectName());
                                    m.setResDept("督查部门");
                                    m.setNodeId(ewn.getNodeSysId());
                                    m.setState("0");
                                    messages.add(m);
                                }
                            }
                        }
                        ms.batchSave(messages);*/
//                        }
                        messageMumber = status;
                        ewn.setMessageMumber(messageMumber + "");
                        ewn.setStatus(status + "");
                        ewns.update(ewn);
                    }
                }
            }
        }else{
            //周末的时候不发短信，但是可以校验更新逾期记录表的经办人跟责任人的信息
            for (EarlyWarningNode earlyWarningNode : list) {
                String nodeSysId = earlyWarningNode.getNodeSysId();
                NodeNewschedules node = nodeNewschedulesService.getById(nodeSysId);
                earlyWarningNode.setOperatorPhone(node.getOperatorPhone());
                earlyWarningNode.setOperatorUser(node.getOperatorUser());
                earlyWarningNode.setResUserPhone(node.getResUserPhone());
                earlyWarningNode.setResUser(node.getResUser());
                earlyWarningNode.setResDept(node.getResDept());
            }
            ewns.batchUpdate(list);
        }
        logger.info(DateUtils.getDateTime() + "*****************定时任务结束*****************");
        System.out.println(DateUtils.getDateTime() + "*****************定时任务结束*****************");
    }

    /**
     * 发送确定节点信息
     */
    public void confirmNodeSMS() throws ParseException {
        if (!DateUtil.isWEEK(new Date())) {
            logger.info(DateUtils.getDateTime() + "*****************定时任务开始，发送确定节点信息*****************");
            System.out.println(DateUtils.getDateTime() + "*****************定时任务开始，发送确定节点信息*****************");
            List<NodeNewschedules> list = nodeNewschedulesService.getNodeState();
            for (NodeNewschedules nns : list) {
                NewProjects np = nService.getById(nns.getProjectId());
                if (ObjectUtils.isNotBlank(np) && ObjectUtils.isNotBlank(nns.getOperatorUser()) && ObjectUtils.isNotBlank(nns.getOperatorPhone()) && "1".equals(nns.getType())) {
                    Map<String, Object> ma = mu.confirmTaskMessage(nns.getOperatorUser(), nns.getOperatorPhone(), "《" + np.getName() + "》", nns.getNodeId());
                    if ("0".equals(ma.get("code").toString())) {
                        net.huashitong.user.entity.Message m = new net.huashitong.user.entity.Message();
                        m.setRecipients(nns.getOperatorUser());
                        m.setText(ma.get("text").toString());
                        m.setType("0");
                        m.setPhone(nns.getOperatorPhone());
                        m.setMsg(ma.get("msg").toString());
                        m.setProjectName(np.getName());
                        m.setResDept(nns.getResDept());
                        ms.save(m);
                    }
                }
            }

            /*String updateScore = taskjobService.updateAllTaskRespAndSupervisionScore();
            if ("ok".equals(updateScore)) {
                logger.info(DateUtils.getDateTime() + "*****************更新督查任务得分完成*****************");
            }
            //更新汇总得分
            scoreSummaryService.updateSummaryScore();*/

            logger.info(DateUtils.getDateTime() + "*****************定时任务结束*****************");
            System.out.println(DateUtils.getDateTime() + "*****************定时任务结束*****************");
        }
    }

    /**
     * 预警提示发短信
     *
     * @throws ParseException
     */
    public void remindSMS() throws ParseException {

        DateFormat format = new SimpleDateFormat("yyyy.MM.dd");
        logger.info(DateUtils.getDateTime() + "*****************定时任务开始预警提示发短信*****************");
        //查找所有有效进行中的小节点
        List<NodeNewschedules> list = nodeNewschedulesService.getNodeInfo(null, "2", "1", "1");
        for (NodeNewschedules nodeNewschedules : list) {
            String planBeginDate = nodeNewschedules.getPlanBeginDate();             //获取计划开始时间
            String planTime = nodeNewschedules.getPlanTime();                       //计划用时
            int planTimeInt = Integer.parseInt(StringUtils.isBlank(planTime) ? "0" : planTime);
            if (StringUtils.isBlank(planBeginDate)) {
                planBeginDate = format.format(new Date());
                nodeNewschedules.setPlanBeginDate(planBeginDate);       //设置新的计划开始时间

                System.out.println("更新计划开始时间");
            }
            Date startDate = format.parse(planBeginDate);
            List<Date> DateList = DateUtil.getBetweenDates(startDate, new Date());
            int usedTime = DateUtil.getStatistics(DateList);            //除去周末两天项目至今所用的时间（天）

            MessageFilter msgFilter = new MessageFilter();
            msgFilter.setText("任务即将到期");
            msgFilter.setType("3");
            msgFilter.setNodeId(nodeNewschedules.getSysId());
            List<Message> msgs = ms.getMessageInfoNoPage(msgFilter);
            if (planTimeInt > 5) {
                // 5天以上的，60%/80%各提醒一次
                double finalVal = usedTime * 1.0 / planTimeInt * 100;
                if (finalVal >= 60.0 && finalVal < 80.0) {

                    //时间大于60%小于80%，如未发预警短信则发送，否则不发送。
                    if (msgs.size() < 1) {
                        NewProjects np = nService.getById(nodeNewschedules.getProjectId());
                        //发送预警提醒短信
                        Map<String, Object> ma = mu.remindMessage(nodeNewschedules.getOperatorUser(),
                                nodeNewschedules.getOperatorPhone(),
                                "《" + np.getName() + "》",
                                nodeNewschedules.getNodeId(),
                                nodeNewschedules.getNodeName());
                        if ("0".equals(ma.get("code").toString())) {
                            net.huashitong.user.entity.Message m = new net.huashitong.user.entity.Message();
                            m.setRecipients(nodeNewschedules.getOperatorUser());
                            m.setText(ma.get("text").toString());
                            m.setType("3");
                            m.setPhone(nodeNewschedules.getOperatorPhone());
                            m.setMsg(ma.get("msg").toString());
                            m.setNodeId(nodeNewschedules.getSysId());
                            m.setProjectName(np.getName());
                            m.setResDept(nodeNewschedules.getResDept());
                            ms.save(m);
                        }
                    }
                } else if (finalVal >= 80.0 && finalVal < 100.0) {
                    //时间大于80%，如未发预警短信则发送，发送满两条后不发送。
                    if (msgs.size() < 2) {
                        NewProjects np = nService.getById(nodeNewschedules.getProjectId());
                        //发送预警提醒短信提醒短信
                        Map<String, Object> ma = mu.remindMessage(nodeNewschedules.getOperatorUser(),
                                nodeNewschedules.getOperatorPhone(),
                                "《" + np.getName() + "》",
                                nodeNewschedules.getNodeId(),
                                nodeNewschedules.getNodeName());
                        if ("0".equals(ma.get("code").toString())) {
                            net.huashitong.user.entity.Message m = new net.huashitong.user.entity.Message();
                            m.setRecipients(nodeNewschedules.getOperatorUser());
                            m.setText(ma.get("text").toString());
                            m.setType("3");
                            m.setPhone(nodeNewschedules.getOperatorPhone());
                            m.setMsg(ma.get("msg").toString());
                            m.setNodeId(nodeNewschedules.getSysId());
                            m.setProjectName(np.getName());
                            m.setResDept(nodeNewschedules.getResDept());
                            ms.save(m);
                        }
                    }
                }
            } else {
                if (usedTime == planTimeInt - 1) {
                    //时间为逾期前一天，如未发预警短信则发送，否则不发送。
                    if (msgs.size() < 1) {
                        NewProjects np = nService.getById(nodeNewschedules.getProjectId());
                        //发送预警提醒短信
                        Map<String, Object> ma = mu.remindMessage(nodeNewschedules.getOperatorUser(),
                                nodeNewschedules.getOperatorPhone(),
                                "《" + np.getName() + "》",
                                nodeNewschedules.getNodeId(),
                                nodeNewschedules.getNodeName());
                        if ("0".equals(ma.get("code").toString())) {
                            net.huashitong.user.entity.Message m = new net.huashitong.user.entity.Message();
                            m.setRecipients(nodeNewschedules.getOperatorUser());
                            m.setText(ma.get("text").toString());
                            m.setType("3");
                            m.setPhone(nodeNewschedules.getOperatorPhone());
                            m.setMsg(ma.get("msg").toString());
                            m.setNodeId(nodeNewschedules.getSysId());
                            m.setProjectName(np.getName());
                            m.setResDept(nodeNewschedules.getResDept());
                            ms.save(m);
                        }
                    }
                }
            }
        }
        //测试
//        DateFormat format = new SimpleDateFormat("yyyy.MM.dd");
//        Date bdate = format.parse("2019.11.08");
//        List<Date> DateList = DateUtil.getBetweenDates(bdate, new Date());
//        int usedTime = DateUtil.getStatistics(DateList);     //除去周末两天项目至今所用的时间（天）
//        double finalVal = usedTime / (20 * 1.0) * 100;
    }

    /**
     * 更新项目信息
     */
    public void updateProject() {
        logger.info(DateUtils.getDateTime() + "*****************定时任务开始*****************");
        System.out.println(DateUtils.getDateTime() + "*****************定时任务开始*****************");
        List<NewProjects> np = nService.query();
        for (NewProjects n : np) {
            /*
            List<NodeNewschedules> nns = nodeNewschedulesService.getNodeByProjectId(n.getSysId());
            for (NodeNewschedules ns : nns) {
                if ("政府投资交通水利类".equals(n.getNatureTypeDetail()) && "2".equals(ns.getStatus()) && "33.2".equals(ns.getNodeId())) {
                    if (!"4".equals(n.getStatus())) {
                        System.out.print("#####项目名称####" + n.getName());
                        n.setStatus("4");
                        n.setFactFinishDate(DateUtil.getDate());
                        nService.update(n);
                    }
                } else if ("土地收储类".equals(n.getNatureTypeDetail()) && "2".equals(ns.getStatus()) && "25.2".equals(ns.getNodeId())) {
                    if (!"4".equals(n.getStatus())) {
                        System.out.print("#####项目名称####" + n.getName());
                        n.setStatus("4");
                        n.setFactFinishDate(DateUtil.getDate());
                        nService.update(n);
                    }

                } else if ("2".equals(ns.getStatus()) && "36.2".equals(ns.getNodeId())) {
                    if (!"4".equals(n.getStatus())) {
                        System.out.print("#####项目名称####" + n.getName());
                        n.setStatus("4");
                        n.setFactFinishDate(DateUtil.getDate());
                        nService.update(n);
                    }
                }
            }
            */
        }

//        scoreSummaryService.updateSummaryScore();
        logger.info(DateUtils.getDateTime() + "*****************定时任务结束*****************");
        System.out.println(DateUtils.getDateTime() + "*****************定时任务结束*****************");
    }

    //开启节点任务
    public void updateNode() throws ParseException {
        if (!DateUtil.isWEEK(new Date())) {
            //查询大节点，确认需要未开始
            /*
            List<NodeNewschedules> list = nodeNewschedulesService.queryList();
            if (ObjectUtils.isNotBlank(list)) {
                for (NodeNewschedules nn : list) {
                    List<NodeNewschedules> lists2 = nodeNewschedulesService.getListByPreNodeId2(nn.getPreNodeId(), nn.getProjectId());
                    if (ObjectUtils.isNotBlank(lists2)) {
                        int ss = 0;
                        for (NodeNewschedules nnss2 : lists2) {
                            if ("2".equals(nnss2.getStatus()) || "2".equals(nnss2.getState())) {
                                ss++;
                            } else {
                                break;
                            }
                        }
                        if (lists2.size() == ss) {
                            nn.setStatus("1");
                            nn.setPlanBeginDate(DateUtil.getDate());
                            nodeNewschedulesService.update(nn);
                            NodeNewschedules smallNns = nodeNewschedulesService.getNnsByProjectIdAndNodeId(nn.getProjectId(), nn.getNodeId() + ".1");
                            if (ObjectUtils.isNotBlank(smallNns)) {
                                smallNns.setStatus("1");
                                smallNns.setPlanBeginDate(DateUtil.getDate());
                                nodeNewschedulesService.update(smallNns);
                                NewProjects np = nService.getById(nn.getProjectId());
                                Map<String, Object> ma = mu.taskMessage(smallNns.getOperatorUser(), smallNns.getOperatorPhone(), "《" + np.getName() + "》", smallNns.getNodeId());
                                if ("0".equals(ma.get("code").toString())) {
                                    Message m = new Message();
                                    m.setRecipients(smallNns.getOperatorUser());
                                    m.setText(ma.get("text").toString());
                                    m.setType("1");
                                    m.setPhone(smallNns.getOperatorPhone());
                                    m.setMsg(ma.get("msg").toString());
                                    m.setProjectName(np.getName());
                                    m.setResDept(smallNns.getResDept());
                                    m.setNodeId(smallNns.getSysId());
                                    ms.save(m);
                                }
                            }
                        }
                    }
                }
            }
            */
        }
    }


    public static void main(String[] args) throws ParseException {
        EarlyWarningService ew = new EarlyWarningService();
        ew.sendEarlyWarningSMS();
    }

    public void sendTackNotice() {
        logger.info(DateUtils.getDateTime() + "*****************定时任务开始*****************");

        //第六天发送提醒短信
        //第八天发送提醒短信
        //最后一天发送提醒短信
    }
}
